package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import Dao.StudentDao;
import Dao.jdbcTools;
import Model.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

@WebServlet("/insertok")
public class insertok extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String age = req.getParameter("age");
        String major = req.getParameter("major");
        String time = req.getParameter("time");

        try {
            InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
            SqlSession sqlSession = factory.openSession();
            StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
            Student student = new Student();
            student.setName(name);student.setSex(sex);student.setAge(Integer.valueOf(age));
            student.setMajor(major);student.setTime(time);
            int add = studentDao.saveStudent(student);
            sqlSession.commit();
            //int add = jdbcTools.add("insert into stuhhh values(null,?,?,?,?,?)", name, sex, age, major, time);
            if (add>0){
                List<Student> list = studentDao.findAll();
                //List<Student> list = jdbcTools.selectall("select * from stuhhh", Student.class);
                req.setAttribute("list",list);
                req.getRequestDispatcher("showlist4.jsp").forward(req,resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
